package main

import (
	"gitee.com/k8sio/cnkit/payloadhub"
	"log"
	"time"
)

func init() {
	log.SetFlags(log.Lshortfile | log.LstdFlags)
}

func main() {
	hub := payloadhub.NewPayloadHub()

	// consumer 1
	watcher1 := hub.NewPayloadHubWatcher()
	go func() {
		log.Printf("watcher1 start")
		defer log.Printf("watcher1 quit")

		watcher1.Watcher(func(payload interface{}) {
			log.Printf("watcher1 get %v", payload)
		})
	}()

	// consumer 2
	watcher2 := hub.NewPayloadHubWatcher()
	go func() {
		log.Printf("watcher2 start")
		defer log.Printf("watcher2 quit")

		watcher2.Watcher(func(payload interface{}) {
			log.Printf("watcher2 get %v", payload)
		})
	}()

	// producer
	go func() {
		time.Sleep(time.Millisecond * 10)
		i := 1
		for hub.IsRunning() {
			log.Printf("push %v", i)
			if hub.Push(i) {
				i++
				time.Sleep(999 * time.Millisecond)
			}
		}
	}()

	interval := time.Second * 3
	log.Printf("Stop after %v", interval)
	time.Sleep(interval)

	log.Printf("call watcher1 Stop")
	watcher1.Stop() // Close this Watcher

	log.Printf("call hub Stop")
	hub.Stop() // Close all Watcher and interdict Push

	log.Printf("done")
}
